﻿using Common.Untils;
using HandyControl.Controls;
using Prism.Ioc;
using System;
using System.Security.Principal;
using System.Threading.Tasks;
using System.Windows;
using Tryit.ViewModels;
using Tryit.Views;
using MessageBox = HandyControl.Controls.MessageBox;
using Window = System.Windows.Window;
using Prism.DryIoc;
using SanmaoTools.Common.Untils;
using Tryit.Services;
using System.IO;
using System.Diagnostics;
using Update.Services;

namespace Tryit
{
    /// <summary>
    /// Interaction logic for App.xaml
    /// </summary>
    public partial class App : PrismApplication
    {
        private DatabaseBackupService _backupService;
        private SettingsViewModel _settingsViewModel;
        private Common.Untils.UpdateService _updateService;

        protected override Window CreateShell()
        {
            // 注册全局未处理异常处理器
            AppDomain.CurrentDomain.UnhandledException += CurrentDomain_UnhandledException;
            TaskScheduler.UnobservedTaskException += TaskScheduler_UnobservedTaskException;
            return Container.Resolve<HomeWindow>();
        }

        private void TaskScheduler_UnobservedTaskException(object sender, UnobservedTaskExceptionEventArgs e)
        {
            Exception ex = (Exception)e.Exception;
            Log.WriteLog(ex.StackTrace, ex.Message);
        }

        private void CurrentDomain_UnhandledException(object sender, UnhandledExceptionEventArgs e)
        {
            Exception ex = (Exception)e.ExceptionObject;
            Log.WriteLog(ex.StackTrace, ex.Message);
        }

        protected override void InitializeShell(Window shell)
        {
            if (!IsAdministrator())
            {
                MessageBox.Show("请用管理员模式打开程序！", "Warning", MessageBoxButton.OK, MessageBoxImage.Warning);
                Application.Current.Shutdown();
            }
            else base.InitializeShell(shell);
        }

        protected override void RegisterTypes(IContainerRegistry containerRegistry)
        {
            // 注册更新服务（使用Gitee用户名和仓库名，添加访问令牌）


            containerRegistry.RegisterSingleton<HomeWindow>();
            containerRegistry.RegisterSingleton<HomeWindowViewModel>();
            containerRegistry.RegisterSingleton<TPAutoUploadViewModel>();
            containerRegistry.RegisterSingleton<SettingsViewModel>();
            containerRegistry.RegisterSingleton<InfoSummaryViewModel>();
            containerRegistry.RegisterSingleton<ScheduleViewModel>();
            containerRegistry.RegisterSingleton<ElementManagementViewModel>();
            containerRegistry.RegisterSingleton<ElementEditDialogViewModel>();
            containerRegistry.RegisterSingleton<SqlSugarHelper>();
            containerRegistry.RegisterSingleton<CurveAnalysisViewModel>();
            containerRegistry.RegisterSingleton<CompositionAdjustmentViewModel>();
           
            // 注册模板服务
            containerRegistry.RegisterSingleton<TemplateService>();
           
            containerRegistry.RegisterForNavigation<TPAutoUpload>();
            containerRegistry.RegisterForNavigation<SettingsView>();
            containerRegistry.RegisterForNavigation<InfoSummaryView>();
            containerRegistry.RegisterForNavigation<ScheduleView>();
            containerRegistry.RegisterForNavigation<ElementManagementView>();
            containerRegistry.RegisterForNavigation<ElementEditDialog>();
            containerRegistry.RegisterForNavigation<CurveAnalysisView, CurveAnalysisViewModel>();
            containerRegistry.RegisterForNavigation<CompositionAdjustmentView, CompositionAdjustmentViewModel>();
         
            //containerRegistry.RegisterForNavigation<SummonerInfo>();
            //containerRegistry.RegisterForNavigation<Error>();

        
            containerRegistry.RegisterForNavigation<ElementManagementView, ElementManagementViewModel>();
        }

        public bool IsAdministrator()
        {
            WindowsIdentity identity = WindowsIdentity.GetCurrent();
            WindowsPrincipal principal = new WindowsPrincipal(identity);
            return principal.IsInRole(WindowsBuiltInRole.Administrator);
        }

        protected override async void OnStartup(StartupEventArgs e)
        {
            _updateService = new Common.Untils.UpdateService("zhaosanmao", "sanmao-tools", VersionInfo.Load().Version, "a68ad17ffd26ae45da0a22ea78b78b84");
            var res = await _updateService.CheckForUpdatesAsync();
            if (res.hasUpdate)
            {
                var path = Path.Combine(Environment.CurrentDirectory, "Update.exe");
                if (File.Exists(path))
                {
                    Process.Start(path);
                    Application.Current.Shutdown();
                }
            }
            base.OnStartup(e);

            _backupService = new DatabaseBackupService();
            _settingsViewModel = new SettingsViewModel();

            // 检查是否需要备份数据库
            CheckAndBackupDatabase();
        }

        private async void CheckAndBackupDatabase()
        {
            try
            {
                if (_backupService.ShouldBackupToday(_settingsViewModel.DatabaseBackupDay))
                {
                    var result = await _backupService.BackupDatabaseAsync();
                    if (result)
                    {
                        MessageBox.Success("数据库备份成功", "备份完成");
                    }

                }
            }
            catch (Exception ex)
            {
                MessageBox.Error($"检查备份时发生错误: {ex.Message}", "错误");
            }
        }
    }
}
